
import json

from django import http
from django.core.paginator import Paginator
from django.views import View
from django.http import JsonResponse
from IHome.settings.dev import logger
from apps.address.models import Area
from apps.houses.utils import house_to_dict
from .models import House, Facility, HouseImage
from IHome.utils.fastdfs.demo import client
from django.conf import settings

#房屋详情
class HouseDetail(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errno': '4103', 'errmsg': "房屋信息查询失败"})

        house_dict = house_to_dict(house)

        return http.JsonResponse(
            {'errno': 0, 'errmsg': "OK", 'data': {"user_id": request.user.id, "house": house_dict}})

# 增加房屋图片
class AddPicture(View):

    def post(self, request, house_id):

        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        try:
            image = request.FILES['house_image'].read()
        except Exception as e:
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})
        ret = client.upload_by_buffer(image)
        if not ret:
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})
        if ret['Status'] != 'Upload successed.':
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        url = settings.FDFS_BASE_URL + ret['Remote file_id']
        try:
            house_image = HouseImage.objects.create(house=house, url=url)
            house.index_image_url = house_image.url
            house.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        return JsonResponse({'errno': 0, 'errmsg': "OK", 'data': {"url": url}})

# 新增房源
class AddHouseView(View):

    def post(self, request):

        response_dic = json.loads(request.body.decode())
        title = response_dic.get('title')
        price = response_dic.get('price')
        area_id = response_dic.get('area_id')
        address = response_dic.get('address')
        room_count = response_dic.get('room_count')
        acreage = response_dic.get('acreage')
        unit = response_dic.get('unit')
        capacity = response_dic.get('capacity')
        beds = response_dic.get('beds')
        deposit = response_dic.get('deposit')
        min_days = response_dic.get('min_days')
        max_days = response_dic.get('max_days')
        facility = response_dic.get('facility')

        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days, facility]):
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})
        try:
            area = Area.objects.get(pk=area_id)
        except Exception as e:
            logger.erroe(e)
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        try:
            facilities = Facility.objects.filter(id__in=facility)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        try:
            house = House.objects.create(
                                            user_id = 1,
                                            title = title,
                                            price = price,
                                            area = area,
                                            address = address,
                                            room_count = room_count,
                                            acreage = acreage,
                                            unit = unit,
                                            capacity = capacity,
                                            beds = beds,
                                            deposit = deposit,
                                            min_days = min_days,
                                            max_days = max_days
                                        )
            for fac in facilities:
                house.facilities.add(fac)
            house.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        return JsonResponse({'errno': '0', 'errmsg': "Ok", 'data': {"house_id": house.pk}})

# 显示用户房源
class HouseView(View):

    def get(self, request):

        user = request.user
        try:
            house_list = House.objects.filter(user=user)
        except Exception as e:
            logger.error(e)
        else:
            data = []
            for house in house_list:
                dic = {
                    'address': house.address,
                    'area_name': house.area.name,
                    'ctime': house.create_time,
                    'house_id': house.pk,
                    'img_url': house.index_image_url,
                    'order_count': house.order_count,
                    'price': house.price,
                    'room_count': house.room_count,
                    'title': house.title,
                    'user_avatar': house.user.real_name
                }
                data.append(dic)

        return JsonResponse({
                                'errmsg':'OK',
                                'errno':'0',
                                'data': data
                            })

# 房屋搜索
class SearchHouseView(View):

    def get(self, request):

        aid = self.request.GET.get('aid')
        sd = self.request.GET.get('sd')
        ed = self.request.GET.get('ed')
        sk = self.request.GET.get('sk')
        page = self.request.GET.get('p')

        if not all([aid, sd, ed]):
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        order_dic = {
            'booking': 'order_count',
            'price-inc': 'price',
            'price_des': '-price',
        }

        try:
            area = Area.objects.get(id=aid)
            houses_list = area.house_set.all().order_by(order_dic.get(sk, 'price'))
        except Exception as e:
            return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

        houses_unbooked = []
        for house in houses_list:
            # orders = house.order_set.filter(Q(begin_date__range=[sd, ed]) | Q(end_data__range=[sd, ed]))
            # if orders:
            #     continue
            houses_unbooked.append(house)

            paginator = Paginator(houses_unbooked, 2)
            try:
                page_houses = paginator.page(page)
                print(page_houses)
            except Exception as e:
                return JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})

            house_data = []
            for house in page_houses:
                dic = {
                    'house_id': house.pk,
                    'order_count': house.order_count,
                    'title': house.title,
                    'ctime': house.create_time,
                    'price': house.price,
                    'area_name': house.area.name,
                    'address': house.address,
                    'room_count': house.room_count,
                    'img_url': house.index_image_url,
                    'user_avatar': house.user.avatar_url,
                }
                house_data.append(dic)

            return JsonResponse({
                'data': {'total_page': paginator.num_pages, 'houses': house_data},
                'errmsg': '请求成功',
                'errno': '0'
            })


class HouseIndex(View):
    '''房屋首页'''

    def get(self, request):

        user = request.user
        # 查询房屋信息 按照房屋订单数倒叙排列
        try:
            houses = House.objects.all().order_by('-order_count')
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'errmsg': 'PARAMERR', 'errno': '4103'})


        # 拼接JSON数据返回
        houses_dict = []
        for house in houses:
            houses_dict.append({
                "house_id": house.id,
                "title": house.title,
                "price": house.price,
                "area_name": house.area.name,
                "img_url": house.index_image_url if house.index_image_url else "",
                "room_count": house.room_count,
                "order_count": house.order_count,
                "address": house.address,
                "user_avatar": '',
                "ctime": house.create_time.strftime("%Y-%m-%d")
            })

        return http.JsonResponse({'errno': '0', 'errmsg': "OK", 'data': houses_dict})